/**
 * 链表节点（单链表）
 * 
 * @author shuyuan.dai 2021-02-04
 */
class LinkedNode {
    constructor(value, next = null) {
        this.value = value;
        this.next = next;
    }

    get val() {
        return this.value;
    }

    add(value) {
        let node = new LinkedNode(value, this.next);
        return this.next = node;
    }

    findUtil2End(value) {
        let p = this;
        while(p != null) {
            if(p.value == value) {
                return p;
            }
            p = p.next;
        }
        return null;
    }

    reverse(prePointer = null) {
        let pre = prePointer, 
            cur = this, 
            back = null;
        while(cur != null) {
            back = cur.next;
            cur.next = pre;
            pre = cur;
            cur = back;
        }
        return pre;
    }

    remove() {
        if(this.next != null) {
            this.next = this.next.next;
            return true;
        }
        return false;
    }

    toString() {
        let p = this, result = [];
        while(p != null) {
            result.push(p.value);
            p = p.next;
        }
        return `${result.join('->')}`;
    }
}

exports.LinkedNode = LinkedNode;